<?php

namespace App\Http\Service;

use App\Http\Util\RandomHelper;
use App\Http\Util\Result;
use App\Model\LimitRecord;
use App\Model\OrderDetail;
use App\Model\OrderList;
use App\Model\OrderSetting;
use App\Model\OrderNote;
use App\Model\PromoteGive;
use App\Model\PromoteDerate;
use App\Model\TempReceiver;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;

trait ServiceOrderDetail{

    /**
     * 订单详细商品
     * czs
     */
    public static function goodsDetail($orderId) {
        $goods = DB::table('order_details as a')
            ->where('a.order_id',$orderId)
            ->leftJoin('products as b','b.id','=','a.product_id')
            ->leftJoin('promotions as c','c.id','=','b.promotion_id')
            ->leftJoin('categories as e','e.id','=','b.category_id')
            ->leftJoin('pictures as f','f.id','=','b.cover_id')
            ->select('a.*','b.name as bname','b.price as bprice','b.vip_price','c.discount','e.category','f.small_img')
            ->get();
        return Result::success()->setData($goods);
    }
    /**
     * 确认支付订单
     * czs
     */
    public static function confirmOrder($input, $id) {
        $note['order_id'] = $id;
        $note['note'] = $input['note'];
        $note['status'] = 2;
        $data['status'] = 2;
        $data['pay_time'] = time();
        DB::beginTransaction();
        try {
            OrderNote::create($note);
            OrderList::where("id", $id)->update($data);
            DB::commit();
        } catch (Exception $e){
            DB::rollback();
            throw $e;
        }
        return Result::success()->setData("保存成功！");
    }

    /**
     * 满足满减总量
     * czs
     */
    public static function deratePrice($orderId) {
        $goods = DB::table('order_details as a')
            ->where('a.order_id',$orderId)
            ->where('c.is_derate',1)
            ->leftJoin('products as b','b.id','=','a.product_id')
            ->leftJoin('promotions as c','c.id','=','b.promotion_id')
            ->select('a.*')
            ->get();
        return Result::success()->setData($goods);
    }

    /**
     * 满足满送总量
     * czs
     */
    public static function givePrice($orderId) {
        $goods = DB::table('order_details as a')
            ->where('a.order_id',$orderId)
            ->where('c.is_give',1)
            ->leftJoin('products as b','b.id','=','a.product_id')
            ->leftJoin('promotions as c','c.id','=','b.promotion_id')
            ->select('a.*')
            ->get();
        return Result::success()->setData($goods);
    }

    /**
     * 总价
     * czs
     */
    public static function allPrice($orderId) {
        $goods = DB::table('order_details as a')
            ->where('a.order_id',$orderId)
            ->select('a.*')
            ->get();
        return Result::success()->setData($goods);
    }

    /**
     * wap提交订单
     * czs
     */
    public static function finalOrder($orderId,$typeId) {
        //总价
        $allPrice = OrderDetail::allPrice($orderId)->getData();
        $all = 0;
        foreach ($allPrice as $v) {
            $all += $v->price*$v->num;
        }
        $data['status'] = 1;
        $numeric = '01234567890123456789';
        $data['order_num'] = substr(str_shuffle($numeric),0,16);
        $data['order_time'] = time();
        if ($typeId==1) {
            //满减活动
            $deratePrice = OrderDetail::deratePrice($orderId)->getData();
            $canDeratePrice = 0;
            foreach ($deratePrice as $v) {
                $canDeratePrice += $v->price*$v->num;
            }
            if ($canDeratePrice) {
                $derate = PromoteDerate::get();
                $effect = 0;
                $cheap = 0;
                foreach ($derate as $v) {
                    if ($canDeratePrice>=$v->effect_amount) {
                        if ($v->effect_amount>=$effect) {
                            $effect = $v->effect_amount;
                            $cheap = $v->cheap_amount;
                        }
                    }
                }
                $all = $all-$cheap;
                $postage = DB::table('order_lists')->where('id',$orderId)->pluck('postage');
                if (!empty($postage)) {
                    $data['total_price'] = $all+$postage;
                } else {
                    $data['total_price'] = $all;
                }
                $data['promote_type'] = 1;
                DB::table('order_lists')->where('id',$orderId)->update($data);
            }
            $childs = DB::table('order_details')
                ->where('order_id',$orderId)
                ->get();
            foreach ($childs as $v) {
                DB::table('products')->where('id',$v->product_id)->decrement('inventory', $v->num);
                DB::table('cart_details')->where('id',$v->cart_id)->delete();
            }
            return Result::success();
        } elseif ($typeId==2) {
            //满送活动
            $givePrice = OrderDetail::givePrice($orderId)->getData();
            $canGivePrice = 0;
            foreach ($givePrice as $v) {
                $canGivePrice += $v->price*$v->num;
            }
            if ($canGivePrice) {
                $give = PromoteGive::get();
                $effect2 = 0;
                foreach ($give as $v) {
                    if ($canGivePrice>=$v->effect_amount) {
                        if ($v->effect_amount>=$effect2) {
                            $effect2 = $v->effect_amount;
                            $num = $v->num;
                        }
                    }
                }
                if (!empty($num)) {
                    $data['card_num'] = $num;
                }
                $postage = DB::table('order_lists')->where('id',$orderId)->pluck('postage');
                if (!empty($postage)) {
                    $data['total_price'] = $all+$postage;
                } else {
                    $data['total_price'] = $all;
                }
                $data['promote_type'] = 2;
                DB::table('order_lists')->where('id',$orderId)->update($data);
            }
            $childs = DB::table('order_details')
                ->where('order_id',$orderId)
                ->get();
            foreach ($childs as $v) {
                DB::table('products')->where('id',$v->product_id)->decrement('inventory', $v->num);
                DB::table('cart_details')->where('id',$v->cart_id)->delete();
            }
            return Result::success();
        } else {
            $postage = DB::table('order_lists')->where('id',$orderId)->pluck('postage');
            if (!empty($postage)) {
                $data['total_price'] = $all+$postage;
            } else {
                $data['total_price'] = $all;
            }
            DB::table('order_lists')->where('id',$orderId)->update($data);
            $childs = DB::table('order_details')
                ->where('order_id',$orderId)
                ->get();
            foreach ($childs as $v) {
                DB::table('products')->where('id',$v->product_id)->decrement('inventory', $v->num);
                DB::table('cart_details')->where('id',$v->cart_id)->delete();
            }
            return Result::success();
        }
    }

    /**
     * 确认发货
     * czs
     */
    public static function deliveOrder($input,$id) {
        $order2['company_id'] = $input['company_id'];
        $order2['waybill'] = $input['waybill'];
        $order2['order_id'] = $id;
        $order['status'] = 3;
        $order['delive_time'] = time();
        $note['order_id'] = $id;
        $note['note'] = $input['note'];
        $note['status'] = 3;
        DB::beginTransaction();
        try {
            OrderNote::create($note);
            OrderList::where("id", $id)->update($order);
            DB::table('order_waybills')->insert($order2);
            DB::commit();
        } catch (Exception $e){
            DB::rollback();
            throw $e;
        }
        return Result::success()->setData("保存成功！");
    }

    /**
     * 确认收货
     * czs
     */
    public static function receiveOrder($input, $id) {
        $note['order_id'] = $id;
        $note['note'] = $input['note'];
        $note['status'] = 4;
        $data['status'] = 4;
        $data['complete_time'] = time();
        DB::beginTransaction();
        try {
            OrderNote::create($note);
            OrderList::where("id", $id)->update($data);
            DB::commit();
        } catch (Exception $e){
            DB::rollback();
            throw $e;
        }
        return Result::success()->setData("保存成功！");
    }

    /**
     *获取订单设置
     * czs
     */
    public static function getSetting() {
        $res = OrderSetting::first();
        return Result::success()->setData($res);
    }

    /**
     * 保存订单设置
     * czs
     */
    public static function updateSetting($input) {
        $res = OrderSetting::where('id', 1)->update($input);
        return Result::success()->setData($res);
    }

    /**
     * web订单详情
     * czs
     */
    public static function forPayDetail($id) {
        $model = DB::table('order_lists as a')->where('a.id',$id)->where('a.status',1);
        $list = $model
            ->select('a.*')
            ->get();
        return Result::success()->setData($list[0]);
    }

    /**
     * web订单详情
     * czs
     */
    public static function forDeliveDetail($id) {
        $model = DB::table('order_lists as a')->where('a.id',$id);
        $list = $model
            ->select('a.*')
            ->get();
        return Result::success()->setData($list[0]);
    }

    /**
     * web订单详情
     * czs
     */
    public static function forReceiveDetail($id) {
        $model = DB::table('order_lists as a')->where('a.id',$id);
        $list = $model
            ->leftJoin('order_waybills as d','d.order_id','=','a.id')
            ->leftJoin('post_companies as e','e.id','=','d.company_id')
            ->select('a.*','e.code','e.name as ename','d.waybill')
            ->get();
        return Result::success()->setData($list[0]);
    }

    /**
     * web订单详情
     * czs
     */
    public static function completeDetail($id) {
        $model = DB::table('order_lists as a')->where('a.id',$id);
        $list = $model
            ->select('a.*')
            ->get();
        return Result::success()->setData($list[0]);
    }

    /**
     * @param $code
     * @param $waybill
     * @return array|bool
     * web物流
     */
    public static  function flowList($code, $waybill)
    {
        $url = "https://m.kuaidi100.com/query?type=$code&postid=$waybill&id=1&valicode=&temp=".rand(10000,99999);
        $ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		curl_close($ch);
		$jsoninfo = json_decode($output, true);
		return $jsoninfo['data'];
    }
	

    /**
     * wap立即购买
     * czs
     */
    public static function inputOrder($goodId,$num,$memberId) {
        $product = DB::table('products as a')
            ->where('a.id',$goodId)
            ->leftJoin('promotions as b','a.promotion_id','=','b.id')
            ->select('b.limit_num','a.inventory','a.limit_num','a.forever_limit','a.post_type')
            ->first();
        if ($num>$product->limit_num) {
            return Result::failure()->setMsg('单次最多购买'.$product->limit_num.'件！');
        }
        $forever = DB::table('limit_records')
            ->where('product_id',$goodId)
            ->where('member_id',$memberId);
        if (!empty($product->forever_limit)) {
            if (empty($forever->count())) {
                if ($num > $product->forever_limit) {
                    return Result::failure()->setMsg('限购' . $product->forever_limit . '件！');
                }
            } else {
                if ($num + $forever->pluck("shop_num") > $product->forever_limit) {
                    return Result::failure()->setMsg('已超出限购！');
                }
            }
        }
        $numHave = DB::table('order_lists as a')
            ->where('a.member_id',$memberId)
            ->leftJoin('order_details as b','b.order_id','=','a.id')
            ->where('b.product_id',$goodId)
            ->where('a.status','<>',9)
            ->sum('b.num');
        $nums = $num+$numHave;
        if (!empty($product->limi_num)&&$nums>$product->limi_num) {
            return Result::failure()->setMsg('已超出限购数量！');
        }
        if ($num>$product->inventory) {
            return Result::failure()->setMsg("库存不足！");
        }
        //清空之前准备的订单
        $model = DB::table('order_lists');
        $model3 = DB::table('order_details');
        $orderList = $model->where('member_id',$memberId)
            ->where('site',2)
            ->where('status',9);
        $count = $orderList->count();
        if(!empty($count)) {
            $order_id = $orderList->pluck('id');
            $orderList->delete();
            $model3->where('order_id',$order_id)->delete();
        }
        //保存联系人
        $data['member_id'] = $memberId;
        $data['status'] = 9;
        $data['site'] = 2;
        $receiver = DB::table('receivers')->where('member_id',$memberId)->where('sequence',1)->first();
        if (empty($receiver)) {
            $receiver = DB::table('receivers')->where('member_id',$memberId)->orderBy('id','desc')->limit(1)->first();
        }
        $data['receiver_id'] = $receiver->id;
        $data['receiver'] = $receiver->name;
        $data['province'] = $receiver->province;
        $data['city'] = $receiver->city;
        $data['phone'] = $receiver->phone;
        $data['address'] = $receiver->address;
        $postage = DB::table('carriage_details')->where('carriage_id',$product->post_type)
            ->where('province',trim($receiver->province))->pluck('fee');
        if (!empty($postage)) {
            $data['postage'] = $postage;
        }
        DB::beginTransaction();
        try {
            $newOrderId = $model->insertGetId($data);
            $item['order_id'] = $newOrderId;
            $item['product_id'] = $goodId;
            $find = DB::table('products as a')
                ->where('a.id',$goodId)
                ->leftJoin('promotions as b','b.id','=','a.promotion_id')
                ->leftJoin('pictures as c','c.id','=','a.cover_id')
                ->leftJoin('categories as d','d.id','=','a.category_id')
                ->select('a.name','a.price','a.vip_price','b.discount','c.small_img','d.category')
                ->first();
            $memberVip = DB::table('members')->where('id',$memberId)->first();
            if (!empty($find->vip_price)&&$memberVip->vip==1) {
                $endPrice = $find->vip_price;
            } else {
                $endPrice = $find->price;
            }
            if (!empty($find->discount)&&$find->discount!=0) {
                $item['price'] = $endPrice*$find->discount;
                $item['one_discount'] = $find->discount;
            } else {
                $item['price'] = $endPrice;
            }
            $item['one_price'] = $endPrice;
            $item['num'] = $num;
            $item['img'] = $find->small_img;
            $item['type_name'] = $find->category;
            $item['good_name'] = $find->name;
            $model3->insert($item);
            DB::commit();
        } catch (Exception $e){
            DB::rollback();
            throw $e;
        }
        return Result::success()->setData('操作成功！');
    }

    /**
     * wap准备订单
     * czs
     */
    public static function readyOrder($post,$memberId) {
        $m = 0;
        $n = 0;
        $o = 0;
        $p = 0;
        foreach ($post as $v) {
            $proId = DB::table('cart_details')->where('id',$v)->pluck('product_id');
            $product = DB::table('products as a')
                ->where('a.id',$proId)
                ->leftJoin('promotions as b','a.promotion_id','=','b.id')
                ->select('b.limit_num','a.inventory','a.forever_limit')
                ->first();
            $num = DB::table('cart_details')
                ->where('id',$v)
                ->pluck('num');
            $numHave = DB::table('order_lists as a')
                ->where('a.member_id',$memberId)
                ->leftJoin('order_details as b','b.order_id','=','a.id')
                ->where('b.product_id',$proId)
                ->where('a.status','<>',9)
                ->sum('b.num');
            $nums = $num+$numHave;
            if (!empty($product->limit_num)&&$nums>$product->limit_num) {
                $m += 1;
            }
            if ($num>$product->inventory) {
                $n += 1;
            }
            if (!empty($product->forever_limit)) {
                $forever = DB::table('limit_records')
                    ->where('product_id', $proId)
                    ->where('member_id', $memberId);
                if (empty($forever->count())) {
                    if ($nums > $product->forever_limit) {
                        $o += 1;
                    }
                } else {
                    if ($nums + $forever->pluck("shop_num") > $product->forever_limit) {
                        $p += $nums;
                    }
                }
            }
        }
        if ($m>=1) {
            return Result::failure()->setMsg('已超出限购数量！');
        }
        if ($n>=1) {
            return Result::failure()->setMsg('库存不足！');
        }
        if ($o>=1) {
            return Result::failure()->setMsg('有商品已超出限购！');
        }
        if ($p>=1) {
            return Result::failure()->setMsg('有商品已超出限购！');
        }
        $model = DB::table('order_lists');
        $model2 = DB::table('cart_details');
        $model3 = DB::table('order_details');
        $orderList = $model->where('member_id',$memberId)
            ->where('site',2)
            ->where('status',9);
        $count = $orderList->count();
        if(!empty($count)) {
            $order_id = $orderList->pluck('id');
            $orderList->delete();
            $model3->where('order_id',$order_id)->delete();
        }
        $data['member_id'] = $memberId;
        $data['status'] = 9;
        $data['site'] = 2;
        $receiver = DB::table('receivers')->where('member_id',$memberId)->where('sequence',1)->first();
        if (empty($receiver)) {
            $receiver = DB::table('receivers')->where('member_id',$memberId)->orderBy('id','desc')->limit(1)->first();
        }
        $data['receiver_id'] = $receiver->id;
        $data['receiver'] = $receiver->name;
        $data['province'] = $receiver->province;
        $data['city'] = $receiver->city;
        $data['phone'] = $receiver->phone;
        $data['address'] = $receiver->address;
        $res = $model2->whereIn('id',$post)->get();
        DB::beginTransaction();
        try {
            $newOrderId = $model->insertGetId($data);
            $item['order_id'] = $newOrderId;
            foreach($res as $v) {
                $item['product_id'] = $v->product_id;
                $find = DB::table('products as a')
                    ->where('a.id',$v->product_id)
                    ->leftJoin('promotions as b','b.id','=','a.promotion_id')
                    ->leftJoin('pictures as c','c.id','=','a.cover_id')
                    ->leftJoin('categories as d','d.id','=','a.category_id')
                    ->select('a.name','a.price','a.vip_price','b.discount','c.small_img','d.category')
                    ->first();
                $memberVip = DB::table('members')->where('id',$memberId)->first();
                if (!empty($find->vip_price)&&$memberVip->vip==1) {
                    $endPrice = $find->vip_price;
                } else {
                    $endPrice = $find->price;
                }
                if (!empty($find->discount)) {
                    $item['price'] = $endPrice*$find->discount;
                } else {
                    $item['price'] = $endPrice;
                }
                $item['num'] = $v->num;
                $item['cart_id'] = $v->id;
                $item['img'] = $find->small_img;
                $item['type_name'] = $find->category;
                $item['good_name'] = $find->name;
                $model3->insert($item);
            }
            DB::commit();
        } catch (Exception $e){
            DB::rollback();
            throw $e;
        }
        return Result::success()->setData('操作成功！');
    }

    /**
     * 确认订单页面
     * czs
     */
    public static function commitOrder($memberId) {
        $model = DB::table('order_lists as a');
        $res = $model->where('a.member_id',$memberId)
            ->where('a.status',9)
            ->where('a.site',2)
            ->leftJoin('receivers as d','d.id','=','a.receiver_id')
            ->select('a.*','d.name as dname','d.phone as dphone','d.address as daddress','d.province','d.city')
            ->first();
        return Result::success()->setData($res);
    }

    /**
     * 分发电子卡
     * @author czs
     * @param $orderId
     * @param $memberId
     * @return bool
     */
    public static function deliveCard($orderId,$memberId) {
        $model = DB::table('order_details as a');
        DB::beginTransaction();
        //电子卡分发
        $res = $model
            ->where('a.order_id',$orderId)
            ->where('c.id',3)
            ->leftJoin('products as b','a.product_id','=','b.id')
            ->leftJoin('categories as c','c.id','=','b.category_id')
            ->select('a.num')
            ->get();
        if (!empty($res)) {
            foreach ($res as $item) {
                $num = $item->num;
                for ($i = 0; $i < $num; $i++) {
                    $res = DB::table('cards')
                        ->where('status', 1)
                        ->where('type', 2)
                        ->where('sell_type', 1)
                        ->where('member_id', 0)
                        ->orderBy('id', 'desc')
                        ->limit(1)
                        ->update(['member_id' => $memberId,'created_at'=>time()]);
                    if($res === false){
                        DB::rollback();
                        return false;
                        break;
                    }
                }
            }
        }
        //分发虚拟平台卡
        $houseCard = DB::table('order_details as a')
            ->where('a.order_id',$orderId)
            ->where('c.id',4)
            ->leftJoin('products as b','a.product_id','=','b.id')
            ->leftJoin('categories as c','c.id','=','b.category_id')
            ->select('a.num','b.house_id','a.id')
            ->first();
        if (!empty($houseCard)) {
            $phone = DB::table('members')->where('id',$memberId)->pluck('phone');
            $content = "";
            for($i=0;$i<$houseCard->num;$i++) {
                $xuni = DB::table('house_cards')
                    ->where('house_id',$houseCard->house_id)
                    ->where('status',1)
                    ->orderBy('id','desc')->limit(1);
                $content = $content.$xuni->pluck('content');
                $res = $xuni->update(['status'=>2,'member_id'=>$memberId,'updated_at'=>time()]);
                if($res === false){
                    DB::rollback();
                    return false;
                    break;
                }

            }
            $alidayu = app('alidayu');//get the instance of alidayu
            $alidayu->setSmsParam(['content'=>$content]);//set the params
            $alidayu->setSmsTemplateCode('SMS_34860239');
            $alidayu->sendCheckCodeSms($phone);//send sms
            $res = OrderDetail::where('id',$houseCard->id)->update(['mark'=>1]);

            if($res === false){
                DB::rollback();
                return false;
            }

        }
        //记录永久限购量
        $forever = DB::table('order_details as a')
            ->where('a.order_id',$orderId)
            ->where('b.forever_limit','<>',0)
            ->leftJoin('products as b','a.product_id','=','b.id')
            ->select('a.num','b.id')
            ->get();
        if (!empty($forever)) {
            foreach($forever as $v) {
                $foreverSel = DB::table('limit_records')->where('member_id',$memberId)
                    ->where('product_id',$v->id);
                if ($foreverSel->count()>0) {
                    $res = DB::table('limit_records')
                        ->where('member_id',$memberId)
                        ->where('product_id',$v->id)
                        ->increment('shop_num', $v->num);
                    if($res === false){
                        DB::rollback();
                        return false;
                        break;
                    }

                } else {
                    $data['member_id'] = $memberId;
                    $data['product_id'] = $v->id;
                    $data['shop_num'] = $v->num;
                    LimitRecord::create($data);
                }
            }
        }
        //判断无其余商品，则改状态为完成
        $count = DB::table('order_details as a')
            ->where('a.order_id',$orderId)
            ->where('b.category_id','<>',3)
            ->where('b.category_id','<>',4)
            ->leftJoin('products as b','a.product_id','=','b.id')
            ->count();
        if (empty($count)) {
            $res = OrderList::where('id',$orderId)->update(['status'=>4]);
            if($res === false){
                DB::rollback();
                return false;
            }
        }

        DB::commit();
        return true;
    }
}


